package com.hlkj.warboot.module_sys.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hlkj.warboot.configurer.properties.SendMailProperties;
import com.hlkj.warboot.configurer.properties.UploadFileProperties;
import com.hlkj.warboot.configurer.util.*;
import com.hlkj.warboot.configurer.util.base.BaseEntityUtil;
import com.hlkj.warboot.configurer.util.base.BaseExceptionUtil;
import com.hlkj.warboot.configurer.util.enums.DictionaryEnum;
import com.hlkj.warboot.configurer.util.excel.admin.DataListenerAdminEntity;
import com.hlkj.warboot.configurer.util.excel.admin.ReadAdminEntity;
import com.hlkj.warboot.module_sys.entity.AdminEntity;
import com.hlkj.warboot.module_sys.entity.MailEntity;
import com.hlkj.warboot.module_sys.service.AdminService;
import com.hlkj.warboot.module_sys.service.AsynService;
import com.hlkj.warboot.module_sys.service.MailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @Description 异步任务接口现类
 * @Author 李星
 * @Date 2019/6/29 23:13
 */
@Service
public class AsynServiceImpl implements AsynService {
    // 存储在服务器上的绝对路径
    @Value("${upload.path}")
    private String uploadPath;
    // 外网访问的绝对路径
    @Value("${upload.domain}")
    private String uploadDomain;

    // 图片上传
    @Value("${upload.image.path}")
    private String imagePath;
    @Value("${upload.image.format}")
    private String imageFormat;
    @Value("${upload.image.size}")
    private long imageSize;

    // 文本上传
    @Value("${upload.text.path}")
    private String textPath;
    @Value("${upload.text.format}")
    private String textFormat;
    @Value("${upload.text.size}")
    private String textSize;

    // 视频上传
    @Value("${upload.video.path}")
    private String videoPath;
    @Value("${upload.video.format}")
    private String videoFormat;
    @Value("${upload.video.size}")
    private String videoSize;

    // excel上传
    @Value("${upload.excel.path}")
    private String excelPath;
    @Value("${upload.excel.format}")
    private String excelFormat;
    @Value("${upload.excel.size}")
    private String excelSize;

    // word上传
    @Value("${upload.word.path}")
    private String wordPath;
    @Value("${upload.word.format}")
    private String wordFormat;
    @Value("${upload.word.size}")
    private String wordSize;

    // pdf上传
    @Value("${upload.pdf.path}")
    private String pdfPath;
    @Value("${upload.pdf.format}")
    private String pdfFormat;
    @Value("${upload.pdf.size}")
    private String pdfSize;

    // 加载配置文件参数：发件邮箱账号
    @Value("${spring.mail.username}")
    private String sender;

    @Resource
    private SendMailProperties sendMailProperties; // 邮件配置参数

    @Resource
    private UploadFileProperties uploadFileProperties; // 配置文件对象

    @Resource
    private JavaMailSender javaMailSender; // 发送邮件接口

    @Resource
    private AdminService adminService;

    @Resource
    private MailService mailService;

    public AsynServiceImpl() {}

    @Override
    public CompletableFuture<JSONObject> sendHtmlMail(MailEntity entity) {
        entity.setSender(sender);
        try {
            // TODO 校验输入的账户是否合法
            QueryWrapper<AdminEntity> queryWrapperForAdmin = new QueryWrapper<>();
            queryWrapperForAdmin.select("email,grade");
            queryWrapperForAdmin.eq("account", entity.getCreateUserAccount());
            AdminEntity adminEntity = adminService.getOne(queryWrapperForAdmin); // 根据 account 查询管理员的 grade和email
            if (adminEntity == null) {
                return CompletableFuture.completedFuture(ResponseUtil.fail("账号输入有误"));
            } else if (!StrUtil.isEffective(adminEntity.getEmail())) {
                return CompletableFuture.completedFuture(ResponseUtil.fail("账户邮件地址为空，请前往个人中心添加"));
            } else {
                entity.setCreateUserGrade(adminEntity.getGrade());
                entity.setReceiver(adminEntity.getEmail());
            }

            // TODO 校验该账户是否可以发送邮件
            QueryWrapper<MailEntity> queryWrapperForMail = new QueryWrapper<>();
            queryWrapperForAdmin.select("createUserAccount,createTime");
            queryWrapperForAdmin.eq("createUserAccount", entity.getCreateUserAccount());
            queryWrapperForAdmin.orderByDesc("createTime");
            List<MailEntity> mailEntityList = mailService.list(queryWrapperForMail); // 根据 createUserAccount 倒序查询邮件的 createUserAccount和createTime
            if (!mailEntityList.isEmpty()) {
                MailEntity mailEntity_1 = mailEntityList.get(0);
                if (DateUtil.dateToDateCharacter(new Date()).equals(DateUtil.dateToDateCharacter(mailEntity_1.getCreateTime()))) {
                    if ( (System.currentTimeMillis() - mailEntity_1.getCreateTime().getTime()) < sendMailProperties.getInterval()) {
                        return CompletableFuture.completedFuture(ResponseUtil.fail("邮件已发送，请不要重复发送"));
                    }
                    if (mailEntityList.size() >= sendMailProperties.getLimit()) {
                        return CompletableFuture.completedFuture(ResponseUtil.fail("当天发送邮件上限"));
                    }
                } else {
                    // 清空该账户下的所有邮件记录
                    mailService.remove(queryWrapperForMail);
                }
            }

            // TODO 校验通过，可以发送邮件。根据模块名称动态生成邮件内容
            if (DictionaryEnum.MAIL_FORGET_PASSWORD.getValue() == entity.getCategory()) { // TODO 忘记密码
                entity.setSubject("找回密码");
                entity.setText(MessageFormat.format("本次修改密码的验证码为: {0}", StrUtil.genRandomStr("mix", 4)));
            } else {
                //
            }

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 是否带附件
            MimeMessageHelper mimeMessageHelper;
            if (StrUtil.isEffective(entity.getAttachment())) {
                mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); // 开启带附件
                String[] filePaths = entity.getAttachment().split(",");
                FileSystemResource file;
                for (String filePath : filePaths) {
                    file = new FileSystemResource(new File(filePath));
                    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                    mimeMessageHelper.addAttachment(fileName, file); // 添加附件
                }
            } else {
                mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
            }
            mimeMessageHelper.setSubject(entity.getSubject()); // 邮件主题
            mimeMessageHelper.setText(entity.getText(), true); // 邮件内容
            mimeMessageHelper.setFrom(entity.getSender());  // 发送者
            mimeMessageHelper.setTo(entity.getReceiver());  // 接收者

            // TODO 发送邮件
            javaMailSender.send(mimeMessage);
            // TODO 添加邮件到数据库
            mailService.save(entity);
            return CompletableFuture.completedFuture(ResponseUtil.success());
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("发送邮件出错：{0}", e.getMessage()));
            return CompletableFuture.completedFuture(ResponseUtil.fail("发送邮件异常"));
        }
    }

//    @Override
//    public CompletableFuture<JSONObject> uploadImage(BaseEntityUtil baseEntityUtil) throws Exception {
//        JSONObject upload = new JSONObject();
//        try {
//            // 保存到服务器的相对路径所在目录
//            String relativePath = MessageFormat.format("{0}/{1}",
//                    uploadFileProperties.getImageRelativePath(), // /static/upload/image
//                    baseEntityUtil.getBaseUploadDirectory());    // cover：头像上传保存的路径
//            // 保存到服务器的文件名（123.png）
//            String saveFileName;
//
//            MultipartFile[] multipartFiles = baseEntityUtil.getBaseUploadMultipartFiles();
//            for (int i = 0; i < multipartFiles.length; i++) {
//                // 文件类型
//                String contentType = multipartFiles[i].getContentType();
//                if (!"image/jpg".equals(contentType) && !"image/png".equals(contentType) && !"image/jpeg".equals(contentType)) {
//                    return CompletableFuture.completedFuture(ResponseUtil.fail("请上传jpg、png格式的图片"));
//                }
//
//                // 文件是否为空
//                if (multipartFiles[i].isEmpty()) {
//                    return CompletableFuture.completedFuture(ResponseUtil.fail("图片文件不存在，请重新上传"));
//                }
//
//                // 文件大小
//                long fileSize = multipartFiles[i].getSize();
//                if (fileSize > uploadFileProperties.getImageSize()) {
//                    return CompletableFuture.completedFuture(ResponseUtil.fail(MessageFormat.format("图片文件不能超过{0}KB", uploadFileProperties.getExcelSize() / 524288)));
//                }
//
//                // 重置图片文件名称
//                String originalFileName = multipartFiles[i].getOriginalFilename(); // 原始文件名，格式：xxx.png
//                int originalFileTypeLastIndex = originalFileName != null ? originalFileName.lastIndexOf(".") : 0;
//                if (originalFileTypeLastIndex == 0) {
//                    return CompletableFuture.completedFuture(ResponseUtil.fail("图片文件名读取失败"));
//                }
//                String originalFileType = originalFileName.substring(originalFileTypeLastIndex + 1).toLowerCase(); // 扩展名
//                // Objects.requireNonNull(originalFileName).split("\\.")[1];
//
//                /**
//                 * @Description TODO 图片上传的业务场景
//                 *
//                 */
//                if ("uploadCover".equals(baseEntityUtil.getBaseUploadCategory())) {
//                    // TODO 1、上传头像，则头像文件名为该用户的账号
//                    saveFileName = MessageFormat.format("{0}.{1}", baseEntityUtil.getBaseAdminAccount(), originalFileType);
//                } else {
//                    // TODO 2、
//                    saveFileName = MessageFormat.format("{0}_{1}.{2}", System.currentTimeMillis(), new Random().nextInt(1000), originalFileType);
//                }
//                // 相对路径 /static/upload/images/cover/123.png
//                upload.put("saveRelativePath_" + i, MessageFormat.format("{0}/{1}", relativePath, saveFileName));
//
//                //获取classes目录绝对路径
//                // idea测试--   /C:/A_JAVA/workspace/osc/snoob/out/production/classes/
//                // 本地tomcat-- /C:/A_JAVA/tomcat/tomcat-8.5.37/webapps/snoob/WEB-INF/classes/
//                String classpath = ResourceUtils.getURL("classpath:").getPath();
//                // C:\A_JAVA\workspace\osc\snoob\out\production\classes
//                // C:\A_JAVA\tomcat\tomcat-8.5.37\webapps\snoob\WEB-INF\classes
//                String absoluteClasspath = new File(classpath).getAbsolutePath();
//                // 保存到服务器的绝对路径（不包含文件名）
//                String imageUploadAbsolutePath = MessageFormat.format("{0}{1}", absoluteClasspath, relativePath);
//                // 创建目录
//                Path path = Paths.get(imageUploadAbsolutePath);
//                if (!Files.exists(path)) {
//                    Files.createDirectories(path);
//                }
//
//                // 上传到服务器 // multipartFile.transferTo( path ); // apache自带文件复制功能
//                path = Paths.get(MessageFormat.format("{0}/{1}", imageUploadAbsolutePath, saveFileName));
//                Files.deleteIfExists(path);
//                Files.copy(multipartFiles[i].getInputStream(), path);
//            }
//            return CompletableFuture.completedFuture(ResponseUtil.success(upload));
//        } catch (Exception e) {
//            LoggerUtil.error(MessageFormat.format("异步上传图片失败：{0}", e.getMessage()));
//            return CompletableFuture.completedFuture(ResponseUtil.fail(e.getCause().getMessage()));
//        }
//    }

    /** 校验文件上传的类型,并生成绝对路径 */
    private JSONObject checkUploadFile(BaseEntityUtil baseEntityUtil) {
        MultipartFile[] multipartFiles = baseEntityUtil.getBaseUploadMultipartFiles();
        MultipartFile multipartFile = null;
        if (multipartFiles.length == 0 || multipartFiles[0].isEmpty()) {
            return ResponseUtil.fail("文件不存在，请重新上传");
        }
        multipartFile =  multipartFiles[0];
        // 上传文件的格式
        String contentType = multipartFile.getContentType();
        if (!StrUtil.isEffective(contentType) || null == contentType) {
            return ResponseUtil.fail("文件格式非法");
        }
        // 上传文件的类型。image,text,video,excel,word,pdf
        String baseUploadFileType = baseEntityUtil.getBaseUploadFileType();
        // 上传文件的业务场景。例如:cover(头像图片上传)
        String baseUploadCategory = baseEntityUtil.getBaseUploadCategory();
        long fileSize = multipartFile.getSize();
        if ("image".equals(baseUploadFileType)) {
            contentType = contentType.replace("image/", "");
            if (!imageFormat.contains(contentType)) {
                return ResponseUtil.fail("请上传jpg、png、jpeg格式的图片");
            }
            if (fileSize > imageSize) {
                return ResponseUtil.fail("图片文件不能超过{0}KB");
                // 194 KB (199,305 字节)
                // CompletableFuture.completedFuture(ResponseUtil.fail(MessageFormat.format("", uploadFileProperties.getExcelSize() / 524288)));
            }
            String relativePath = MessageFormat.format("{0}{1}/{2}/{3}", uploadPath, imagePath, baseUploadCategory, DateUtil.dateToDateCharacter(new Date()));
            FileUtil.createDirectory(relativePath);
            return ResponseUtil.success(relativePath);
        } else if ("text".equals(baseUploadFileType)) {
            return ResponseUtil.fail("上传文件格式非法");
        } else if ("video".equals(baseUploadFileType)) {
            return ResponseUtil.fail("上传文件格式非法");
        } else if ("excel".equals(baseUploadFileType)) {
            return ResponseUtil.fail("上传文件格式非法");
        } else if ("word".equals(baseUploadFileType)) {
            return ResponseUtil.fail("上传文件格式非法");
        } else if ("pdf".equals(baseUploadFileType)) {
            return ResponseUtil.fail("上传文件格式非法");
        } else {
            return ResponseUtil.fail("上传文件格式非法");
        }
    }

    @Override
    public CompletableFuture<JSONObject> uploadFile(BaseEntityUtil baseEntityUtil) throws Exception {
        // 自定义校验规则
        JSONObject checkUploadFile = checkUploadFile(baseEntityUtil);
        if (checkUploadFile.getInteger("code") == 1) {
            return CompletableFuture.completedFuture(checkUploadFile);
        }
        // 上传文件的绝对路径
        String pathStr = checkUploadFile.getString("data");
        JSONObject uploadMsg = new JSONObject();
        JSONArray filePathArray = new JSONArray();
        try {
            MultipartFile[] multipartFiles = baseEntityUtil.getBaseUploadMultipartFiles();
            for (MultipartFile multipartFile : multipartFiles) {
                // 重置图片文件名称
                String originalFileName = multipartFile.getOriginalFilename(); // 原始文件名，格式：xxx.png
                int originalFileTypeLastIndex = originalFileName != null ? originalFileName.lastIndexOf(".") : 0;
                if (originalFileTypeLastIndex == 0) {
                    return CompletableFuture.completedFuture(ResponseUtil.fail("图片文件名读取失败"));
                }
                String originalFileType = originalFileName.substring(originalFileTypeLastIndex + 1).toLowerCase(); // 扩展名
                String fileNewName = baseEntityUtil.getBaseAdminAccount() + UUID.randomUUID();
                String filePath = MessageFormat.format("{0}/{1}.{2}", pathStr, fileNewName, originalFileType);
                filePathArray.add(filePath);
                // 上传到服务器 // multipartFile.transferTo( path ); // apache自带文件复制功能
                Path path = Paths.get(filePath);
                Files.deleteIfExists(path);
                Files.copy(multipartFile.getInputStream(), path);
            }
            uploadMsg.put("domain", uploadDomain);
            uploadMsg.put("filePathArray", filePathArray);
            return CompletableFuture.completedFuture(ResponseUtil.success(uploadMsg));
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("异步上传图片失败：{0}", e.getMessage()));
            return CompletableFuture.completedFuture(ResponseUtil.fail(e.getCause().getMessage()));
        }
    }

    @Override
    public CompletableFuture<JSONObject> importDataByExcel(MultipartFile[] multipartFiles, BaseEntityUtil baseEntityUtil) throws Exception {
        // 文件个数
        int fileLength = multipartFiles.length;
        if (fileLength < 1) {
            return CompletableFuture.completedFuture(ResponseUtil.fail("您还没有选择文件！"));
        }
        if (fileLength > 1) {
            return CompletableFuture.completedFuture(ResponseUtil.fail("每次只能选择一个文件！"));
        }

        // 文件是否为空
        boolean isEmpty = multipartFiles[0].isEmpty();
        if (isEmpty) {
            return CompletableFuture.completedFuture(ResponseUtil.fail("文件内容不能为空！"));
        }

        // 文件大小
        long fileSize = multipartFiles[0].getSize();
        if (fileSize > uploadFileProperties.getExcelSize()) {
            return CompletableFuture.completedFuture(ResponseUtil.fail(MessageFormat.format("Excel文件不能超过{0}M", uploadFileProperties.getExcelSize() / 5242880)));
        }

        // 文件类型
        String contentType = multipartFiles[0].getContentType();
        List<Map<Integer, String>> mapList; // 存储从Excel中读取的数据
        try {
            if ("application/vnd.ms-excel".equals(contentType)) {
                // 解析Excel
                mapList = ExcelPoiUtil.readXLX(multipartFiles[0].getInputStream());
            } else if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)) {
                // 解析Excel
                mapList = ExcelPoiUtil.readXLXS(multipartFiles[0].getInputStream());
            } else {
                return CompletableFuture.completedFuture(ResponseUtil.fail("请上传Excel格式文件！"));
            }

            /*
             * 记录导入状态
             */
            Map<String, String> resultMap = new HashMap<>();
            int sum = mapList.size(); // 总条数
            int successSum = 0; // 记录成功条数
            int failSum = 0; // 记录失败条数
            List<String> failMsg = new ArrayList<>(); // 记录失败信息

            /*
             * TODO 判断模块类型
             */
            int index = 1; // 计数，当前第几条数据
            if ("admin".equals(baseEntityUtil.getBaseUploadCategory())) {
                LoggerUtil.info("导入管理员信息-----------start");
                AdminEntity adminEntity;
                for (Map<Integer, String> integerObjectMap : mapList) {
                    try {
                        adminEntity = new AdminEntity();
                        adminEntity.setAccount(integerObjectMap.get(0)); // 账号
                        adminEntity.setPass("/51EitJllKDiB5LdWQKfkw=="); // 全局默认账号密码，pas123456

                        adminEntity.setGrade(Integer.valueOf(integerObjectMap.get(1))); // 账号等级
                        if (DictionaryEnum.ADMIN_GRADE_SUPER_ADMIN.getValue() == adminEntity.getGrade()) {
                            adminEntity.setGrade(DictionaryEnum.ADMIN_GRADE_SUPER_ADMIN.getValue());
                        } else if (DictionaryEnum.ADMIN_GRADE_PROVINCE.getValue() == adminEntity.getGrade()) {
                            adminEntity.setGrade(DictionaryEnum.ADMIN_GRADE_PROVINCE.getValue());
                        } else if (DictionaryEnum.ADMIN_GRADE_CITY.getValue() == adminEntity.getGrade()) {
                            adminEntity.setGrade(DictionaryEnum.ADMIN_GRADE_CITY.getValue());
                        } else if (DictionaryEnum.ADMIN_GRADE_AREA.getValue() == adminEntity.getGrade()) {
                            adminEntity.setGrade(DictionaryEnum.ADMIN_GRADE_AREA.getValue());
                        } else {
                            throw new BaseExceptionUtil("账号等级缺失");
                        }

                        adminEntity.setActive(Integer.valueOf(integerObjectMap.get(2))); // 账号状态
                        if (DictionaryEnum.ADMIN_STATUS_EFFECTIVE.getValue() == adminEntity.getActive()) {
                            adminEntity.setActive(DictionaryEnum.ADMIN_STATUS_EFFECTIVE.getValue());
                        } else if (DictionaryEnum.ADMIN_STATUS_LOCKED.getValue() == adminEntity.getActive()) {
                            adminEntity.setActive(DictionaryEnum.ADMIN_STATUS_LOCKED.getValue());
                        } else if (DictionaryEnum.ADMIN_STATUS_PROHIBIT.getValue() == adminEntity.getActive()) {
                            adminEntity.setActive(DictionaryEnum.ADMIN_STATUS_PROHIBIT.getValue());
                        } else {
                            throw new BaseExceptionUtil("账号状态缺失");
                        }

                        UpdateWrapper<AdminEntity> updateWrapper = new UpdateWrapper<AdminEntity>();
                        updateWrapper.eq("account", adminEntity.getAccount());
                        boolean status = adminService.saveOrUpdate(adminEntity,updateWrapper); // 根据updateWrapper尝试更新，否继续执行saveOrUpdate(T)方法
                        if (status) {
                            successSum += 1;
                        }
                    } catch (Exception e) {
                        String eMsg = MessageFormat.format("第{0}条数据导入失败：{1}", index, e.getCause().getMessage());
                        LoggerUtil.info(eMsg);
                        failSum += 1;
                        failMsg.add(eMsg);
                    } finally {
                        index += 1;
                    }
                }
                LoggerUtil.info("导入管理员信息-----------end");
            }

            resultMap.put("sum", String.valueOf(sum));
            resultMap.put("successSum", String.valueOf(successSum));
            resultMap.put("failSum", String.valueOf(failSum));
            resultMap.put("failMsg", String.valueOf(failMsg));
            return CompletableFuture.completedFuture(ResponseUtil.success(resultMap));
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("uploadExcel出错：{0}", e.getMessage()));
            return CompletableFuture.completedFuture(ResponseUtil.fail(e.getCause().getMessage()));
        }
    }

    @Override
    public CompletableFuture<JSONObject> importDataByExcelNew(MultipartFile[] multipartFiles, BaseEntityUtil baseEntityUtil) throws Exception {
        // 文件个数
        int fileLength = multipartFiles.length;
        if (fileLength < 1) {
            return CompletableFuture.completedFuture(ResponseUtil.fail("您还没有选择文件！"));
        }
        if (fileLength > 1) {
            return CompletableFuture.completedFuture(ResponseUtil.fail("每次只能选择一个文件！"));
        }

        // 文件是否为空
        boolean isEmpty = multipartFiles[0].isEmpty();
        if (isEmpty) {
            return CompletableFuture.completedFuture(ResponseUtil.fail("文件内容不能为空！"));
        }

        // 文件大小
        long fileSize = multipartFiles[0].getSize();
        if (fileSize > uploadFileProperties.getExcelSize()) {
            return CompletableFuture.completedFuture(ResponseUtil.fail(MessageFormat.format("Excel文件不能超过{0}M", uploadFileProperties.getExcelSize() / 5242880)));
        }

        // 文件类型
        String contentType = multipartFiles[0].getContentType();
        try {
            if (!"application/vnd.ms-excel".equals(contentType) && !"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)) {
                return CompletableFuture.completedFuture(ResponseUtil.fail("请上传Excel格式文件！"));
            }
            /*
             * @Description TODO 导入场景的判断
             */
            if ("admin".equals(baseEntityUtil.getBaseUploadCategory())) {
                // TODO admin管理员导入
                // 导入所有的sheet,跳过2行表头从第3行开始读取数据
                EasyExcel.read(multipartFiles[0].getInputStream(), ReadAdminEntity.class, new DataListenerAdminEntity(adminService)).headRowNumber(2).doReadAll();
                // 导入当前sheet
                //EasyExcel.read(multipartFiles[0].getInputStream(), ReadAdminEntity.class, new DataListenerAdminEntity(adminService)).sheet().headRowNumber(2).doRead();
            }
            return CompletableFuture.completedFuture(ResponseUtil.success("success"));
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("uploadExcel出错：{0}", e.getMessage()));
            return CompletableFuture.completedFuture(ResponseUtil.fail(e.getCause().getMessage()));
        }
    }

    @Override
    public void downloadFile(String source, HttpServletResponse response) throws Exception {
        OutputStream outputStream = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource("static" + File.separator + "upload" + File.separator + "images" + File.separator + source);
            InputStream inputStream = classPathResource.getInputStream();

            byte[] buffer = StrUtil.getByteArray(inputStream); // File file = new File(source); byte[] buffer = getByteArray(new FileInputStream(file));
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(source.getBytes("GBK"), "ISO8859_1"));
            response.addHeader("Content-Length", "" + buffer.length);
            response.setContentType("application/octet-stream");
            outputStream = response.getOutputStream();
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            ResponseUtil.fail("将服务器文件输出到浏览器出错：" + e.getMessage());
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    ResponseUtil.fail(MessageFormat.format("将服务器文件输出到浏览器，关闭流出错：{0}", ioe.getMessage()));
                }
            }
        }
    }

}
